<?php
	require_once('db_fns.php');

	function register($username, $email, $password) {
		//register new peoson with db
		//return true or error message
		
		//connect to db
		$con = db_connect();

		//check if username is unique
		$result = $con->query("select * from user where username='".$username."'");
		if (!$result) {
			throw new Exception("Coult not execute query");
			
		}
		if ($result->num_rows>0) {
			throw new Exception('That username is taken - go back and choose another one.');
			
		}

		//if ok, put in db
		$result - $con->query("insert into user
			values('".$username."', sha1('".$password."'), '".$email."')");

		if (!$result) {
			throw new Exception("Could not register you in database - please try again later.");
			
		}
		return true;
	}

	function login($username, $passwd) {
		//check username and password with db
		//if yes, return true
		//else throw exception
		//
		//connect to db
		$con = db_connect();

		//check if username is unique
		$result = $con->query("select * from user where username='".$username."' and passwd = sha1('".$passwd."')");

		if (!$result) {
			throw new Exception("Could not log you in.");
			
		}
		if ($result->num_rows>0) {
			return true;
		} else {
			throw new Exception('Could not log you in.');
			
		}
	}

	function check_valid_user() {
		//see if somebody is logged in and motify them if not
		if (isset($_SESSION['valid_user'])) {
			echo "Logged in as ".$_SESSION['valid_user']."<br />";
		} else {
			//they are not logged in
			do_html_heading('Problem:');
			echo "Your are not logged in.<br />";
			do_html_url('login.php', 'To Login');
			do_html_footer();
			exit();
		}
	}